package controller.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Company;

public class Dao_Company {
	EntityManager manager;
	
	public boolean save(Company company) {
		manager = Factory.factory().createEntityManager();
		try	{
			manager.getTransaction().begin();			
			manager.merge(company);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}	
	}
	
	public List<Company> listAll(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT c FROM Company c" );
		@SuppressWarnings("unchecked")
		List<Company> company =  query.getResultList();
		manager.close();	
		return company;
	}
	
	public boolean update(Company company){
		try{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(company);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public boolean delete(Company company){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.remove(company);
			manager.getTransaction().commit();
			manager.close();				
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public Company list(int id){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			Company company = manager.find(Company.class, id);
			manager.close();
			return company;
		} catch (Exception e) {
			return null;				
		}
	}
}
